package com.sxbbc.agent.interceptor;

import com.sxbbc.agent.common.CashMapping;
import com.sxbbc.agent.common.MappingUtils;
import com.sxbbc.agent.util.AgentSession;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.core.entity.jz.AgAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 登录拦截器
 * @author leehao
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        AgAgent agent = AgentSession.getAgent(request);
        String type = request.getHeader("X-Requested-With");
        if (agent == null) {
            if ("XMLHttpRequest".equalsIgnoreCase(type)) {
                response.setHeader("sessionstatus", "timeout");
            } else {
                response.sendRedirect(MappingUtils.SHOW_LOGIN);
            }
            return false;
        } else {
            String returnUrl = String.valueOf(request.getServletPath());
            List<String> strs = AgentSession.getMenuUrl(request);
            strs.add(MappingUtils.SHOW_HOME);
            strs.add(MappingUtils.SHOW_UPDATE_PASSWORD);
            strs.add(MappingUtils.UPDATE_PASSWORD);
            strs.add(MappingUtils.SHOW_PROFIT_LIST);
            strs.add(MappingUtils.SHOW_CUSTOMER_LIST);
            strs.add(MappingUtils.SHOW_BUSINESS_LIST);
            strs.add(MappingUtils.QUERY_PROFIT_LIST);
            strs.add(MappingUtils.QUERY_CUSTOMER_LIST);
            strs.add(MappingUtils.QUERY_BUSINESS_LIST);
            strs.add(CashMapping.QUERY_BANK_DETAIL);
            strs.add(CashMapping.QUERY_CASH_DETAIL);
            strs.add(CashMapping.ADD_BANK);
            strs.add(CashMapping.SHOW_ADD_BANK);
            strs.add(CashMapping.DELETE_BANK_BYID);
            strs.add(MappingUtils.SHOW_WELCOME);
            boolean hasPermission = strs.contains(returnUrl);
            if (StringUtils.equalsIgnoreCase("XMLHttpRequest", type)) {
                if (!hasPermission) {
                    throw new ThrowJsonException("您还没有此功能权限不能操作");
                }
            } else {
                if (!hasPermission) {
                    throw new ThrowJsonException("您还没有此功能权限不能操作");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
